
import logging
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.core.cache import cache

logger = logging.getLogger(__name__)

class WebSocketManager:
    """WebSocket连接管理和消息发送工具类"""
    
    @staticmethod
    def send_location_update(location_record):
        """发送位置更新消息"""
        try:
            channel_layer = get_channel_layer()
            group_name = f'order_{location_record.order.id}_tracking'
            
            # 检查是否有活跃的连接
            if not cache.get(f'ws_active_{group_name}'):
                logger.warning(f"No active WebSocket connections for group {group_name}")
                return
                
            message = {
                'type': 'location_update',
                'data': {
                    'location_id': location_record.id,
                    'order_id': location_record.order.id,
                    'coordinates': {
                        'longitude': float(location_record.longitude),
                        'latitude': float(location_record.latitude)
                    },
                    'timestamp': location_record.created_at.isoformat()
                }
            }
            
            async_to_sync(channel_layer.group_send)(
                group_name,
                message
            )
            logger.debug(f"Location update sent to {group_name}")
            
        except Exception as e:
            logger.error(f"Error sending location update: {str(e)}")
            # 重试逻辑可以在这里实现

    @staticmethod
    def track_connection(group_name):
        """跟踪WebSocket连接状态"""
        try:
            # 设置连接活跃标记，有效期5分钟
            cache.set(f'ws_active_{group_name}', True, timeout=300)
        except Exception as e:
            logger.error(f"Error tracking connection: {str(e)}")